import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import {
  Settings,
  Monitor,
  BarChart3,
  Activity,
  Users,
  Zap,
  Bell,
  Palette,
  Layout,
  Clock,
} from 'lucide-react';
import { toast } from 'sonner';

// 个性化设置接口
interface PersonalizationSettings {
  theme: 'light' | 'dark' | 'auto';
  refreshInterval: number; // 秒
  enableNotifications: boolean;
  enableAutoRefresh: boolean;
  defaultLayout: 'grid' | 'list' | 'compact';
  visibleModules: {
    stats: boolean;
    systemMonitor: boolean;
    recentActivity: boolean;
    quickActions: boolean;
    notifications: boolean;
    charts: boolean;
  };
  widgetSizes: {
    stats: 'small' | 'medium' | 'large';
    systemMonitor: 'small' | 'medium' | 'large';
    recentActivity: 'small' | 'medium' | 'large';
    quickActions: 'small' | 'medium' | 'large';
  };
}

// 默认设置
const defaultSettings: PersonalizationSettings = {
  theme: 'light',
  refreshInterval: 30,
  enableNotifications: true,
  enableAutoRefresh: true,
  defaultLayout: 'grid',
  visibleModules: {
    stats: true,
    systemMonitor: true,
    recentActivity: true,
    quickActions: true,
    notifications: true,
    charts: false,
  },
  widgetSizes: {
    stats: 'large',
    systemMonitor: 'large',
    recentActivity: 'medium',
    quickActions: 'small',
  },
};

// 模块配置
const moduleConfigs = [
  {
    key: 'stats' as const,
    name: '数据统计',
    description: '显示系统关键指标和统计数据',
    icon: BarChart3,
    color: 'text-blue-600',
  },
  {
    key: 'systemMonitor' as const,
    name: '系统监控',
    description: '实时监控系统性能和健康状态',
    icon: Monitor,
    color: 'text-green-600',
  },
  {
    key: 'recentActivity' as const,
    name: '最近活动',
    description: '显示系统最新的活动和事件',
    icon: Activity,
    color: 'text-orange-600',
  },
  {
    key: 'quickActions' as const,
    name: '快速操作',
    description: '提供常用功能的快速访问入口',
    icon: Zap,
    color: 'text-purple-600',
  },
  {
    key: 'notifications' as const,
    name: '通知中心',
    description: '显示系统通知和提醒',
    icon: Bell,
    color: 'text-red-600',
  },
  {
    key: 'charts' as const,
    name: '图表分析',
    description: '显示数据可视化图表',
    icon: BarChart3,
    color: 'text-indigo-600',
  },
];

interface PersonalizationSettingsProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  settings: PersonalizationSettings;
  onSettingsChange: (settings: PersonalizationSettings) => void;
}

/**
 * 个性化设置组件
 * 允许用户自定义仪表盘的显示和行为
 */
export const PersonalizationSettings: React.FC<PersonalizationSettingsProps> = ({
  open,
  onOpenChange,
  settings,
  onSettingsChange,
}) => {
  const [localSettings, setLocalSettings] = useState<PersonalizationSettings>(settings);

  // 同步外部设置变化
  useEffect(() => {
    setLocalSettings(settings);
  }, [settings]);

  /**
   * 更新本地设置
   * @param updates 要更新的设置项
   */
  const updateLocalSettings = (updates: Partial<PersonalizationSettings>) => {
    setLocalSettings(prev => ({ ...prev, ...updates }));
  };

  /**
   * 更新模块可见性
   * @param moduleKey 模块键名
   * @param visible 是否可见
   */
  const updateModuleVisibility = (moduleKey: keyof PersonalizationSettings['visibleModules'], visible: boolean) => {
    setLocalSettings(prev => ({
      ...prev,
      visibleModules: {
        ...prev.visibleModules,
        [moduleKey]: visible,
      },
    }));
  };

  /**
   * 更新小部件大小
   * @param widgetKey 小部件键名
   * @param size 大小
   */
  const updateWidgetSize = (widgetKey: keyof PersonalizationSettings['widgetSizes'], size: 'small' | 'medium' | 'large') => {
    setLocalSettings(prev => ({
      ...prev,
      widgetSizes: {
        ...prev.widgetSizes,
        [widgetKey]: size,
      },
    }));
  };

  /**
   * 保存设置
   */
  const handleSave = () => {
    onSettingsChange(localSettings);
    onOpenChange(false);
    toast.success('个性化设置已保存');
  };

  /**
   * 重置为默认设置
   */
  const handleReset = () => {
    setLocalSettings(defaultSettings);
    toast.info('设置已重置为默认值');
  };

  /**
   * 取消更改
   */
  const handleCancel = () => {
    setLocalSettings(settings);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center space-x-2">
            <Settings className="w-5 h-5" />
            <span>个性化设置</span>
          </DialogTitle>
          <DialogDescription>
            自定义您的仪表盘显示和行为偏好
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* 外观设置 */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Palette className="w-4 h-4" />
                <span>外观设置</span>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="theme">主题模式</Label>
                  <Select
                    value={localSettings?.theme || 'light'}
                    onValueChange={(value: 'light' | 'dark' | 'auto') => 
                      updateLocalSettings({ theme: value })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="light">浅色模式</SelectItem>
                      <SelectItem value="dark">深色模式</SelectItem>
                      <SelectItem value="auto">跟随系统</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label htmlFor="layout">默认布局</Label>
                  <Select
                    value={localSettings?.defaultLayout || 'grid'}
                    onValueChange={(value: 'grid' | 'list' | 'compact') => 
                      updateLocalSettings({ defaultLayout: value })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="grid">网格布局</SelectItem>
                      <SelectItem value="list">列表布局</SelectItem>
                      <SelectItem value="compact">紧凑布局</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 行为设置 */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Clock className="w-4 h-4" />
                <span>行为设置</span>
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <Label htmlFor="auto-refresh">自动刷新</Label>
                  <p className="text-sm text-muted-foreground">定期自动更新仪表盘数据</p>
                </div>
                <Switch
                  id="auto-refresh"
                  checked={localSettings?.enableAutoRefresh || false}
                  onCheckedChange={(checked) => 
                    updateLocalSettings({ enableAutoRefresh: checked })
                  }
                />
              </div>
              
              <div className="flex items-center justify-between">
                <div>
                  <Label htmlFor="notifications">启用通知</Label>
                  <p className="text-sm text-muted-foreground">接收系统通知和提醒</p>
                </div>
                <Switch
                  id="notifications"
                  checked={localSettings?.enableNotifications || false}
                  onCheckedChange={(checked) => 
                    updateLocalSettings({ enableNotifications: checked })
                  }
                />
              </div>

              <div>
                <Label htmlFor="refresh-interval">刷新间隔（秒）</Label>
                <Select
                  value={(localSettings?.refreshInterval || 30).toString()}
                  onValueChange={(value) => 
                    updateLocalSettings({ refreshInterval: parseInt(value) })
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="10">10秒</SelectItem>
                    <SelectItem value="30">30秒</SelectItem>
                    <SelectItem value="60">1分钟</SelectItem>
                    <SelectItem value="300">5分钟</SelectItem>
                    <SelectItem value="600">10分钟</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>

          {/* 模块设置 */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Layout className="w-4 h-4" />
                <span>模块设置</span>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {moduleConfigs.map((module) => {
                  const IconComponent = module.icon;
                  const isVisible = localSettings?.visibleModules?.[module.key] || false;
                  const hasSize = module.key in (localSettings?.widgetSizes || {});
                  
                  return (
                    <div key={module.key} className="space-y-3">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-3">
                          <IconComponent className={`w-5 h-5 ${module.color}`} />
                          <div>
                            <Label className="font-medium">{module.name}</Label>
                            <p className="text-sm text-muted-foreground">{module.description}</p>
                          </div>
                        </div>
                        <Switch
                          checked={isVisible}
                          onCheckedChange={(checked) => 
                            updateModuleVisibility(module.key, checked)
                          }
                        />
                      </div>
                      
                      {/* 小部件大小设置 */}
                      {isVisible && hasSize && (
                        <div className="ml-8 flex items-center space-x-4">
                          <Label className="text-sm">大小:</Label>
                          <Select
                            value={localSettings?.widgetSizes?.[module.key as keyof PersonalizationSettings['widgetSizes']] || 'medium'}
                            onValueChange={(value: 'small' | 'medium' | 'large') => 
                              updateWidgetSize(module.key as keyof PersonalizationSettings['widgetSizes'], value)
                            }
                          >
                            <SelectTrigger className="w-24">
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="small">小</SelectItem>
                              <SelectItem value="medium">中</SelectItem>
                              <SelectItem value="large">大</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                      )}
                      
                      {module.key !== moduleConfigs[moduleConfigs.length - 1].key && (
                        <Separator />
                      )}
                    </div>
                  );
                })}
              </div>
            </CardContent>
          </Card>
        </div>

        <DialogFooter className="flex justify-between">
          <Button variant="outline" onClick={handleReset}>
            重置默认
          </Button>
          <div className="space-x-2">
            <Button variant="outline" onClick={handleCancel}>
              取消
            </Button>
            <Button onClick={handleSave}>
              保存设置
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export type { PersonalizationSettings };
export { defaultSettings };